package com.thinkgem.jeesite.modules.sys.service;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.modules.sys.dao.*;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.utils.Configuration;
import com.thinkgem.jeesite.modules.sys.utils.NumberGenerator;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by jyy on 2016/10/19 0019.
 */
@Service
public class TbOrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbShopProductDao tbShopProductDao;
    @Autowired
    private TbOrderProductMapper tbOrderProductMapper;
    @Autowired
    private TbShopMapper tbShopMapper;
    @Autowired
    private TbAgentProductMapper tbAgentProductMapper;
    @Autowired
    private TbProductMapper tbProductMapper;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TbSenderDao tbSenderDao;
    @Autowired
    private TbMsgNotifyService tbMsgNotifyService;
    @Autowired
    private TbProductService tbProductService;
    @Autowired
    private TbCategoryService tbCategoryService;

    @Transactional(readOnly = false)
    public TbOrder queryOrder(Integer id) {
        return tbOrderMapper.selectByPrimaryId(id);
    }
    @Transactional(readOnly = false)
    public String queryAddress(TbOrder tbOrder) {
        String address="";
        User user=tbOrderMapper.overseaAddress(tbOrder);
        if(null!=user){
            address=user.getProvinces()+user.getCitys()+user.getAreas()+user.getName();
        }
        return address;
    }
    @Transactional(readOnly = false)
    public  List<TbOrder> selectOrderListById(String ids){
        List<TbOrder> list =new ArrayList<TbOrder>();
        String[] id=ids.split(",");
        for(int i=0;i<id.length;i++){
            TbOrder tt=tbOrderMapper.selectByPrimaryId(Integer.parseInt(id[i]));
            list.add(tt);
        }
        //根据ids得到订单结合
       // List<TbOrder> list=tbOrderMapper.selectOrderListById(params);
        /*for(int i=0;i<list.size();i++){
            TbOrder tt=list.get(i);
            List<TbOrderProduct> productlist=tbOrderProductMapper.queryListOrderProduct(tt.getId());
            tt.setProductList(productlist);
        }*/
        return list;
    }
    //代理商在确认发货时同时修改自己的库存
    @Transactional(readOnly = false)
    public Integer subStoreNum(TbOrderProduct  tbOrderProduct) {
        return tbOrderMapper.subStoreNum(tbOrderProduct);
    }
    @Transactional(readOnly = false)
    public TbOrder get(Integer id) {
        return tbOrderMapper.selectByPrimaryKey(id);
    }
    @Transactional(readOnly = false)
    public Page<TbOrder> findTbOrderByPage(Page<TbOrder> tbOrderPage, TbOrder tbOrder) {

        // 设置默认时间范围，默认当前月
       /*if (tbOrder.getBeginDate() == null){
            tbOrder.setBeginDate(DateUtils.setDays(DateUtils.parseDate(DateUtils.getDate()), 1));
        }
        if (tbOrder.getEndDate() == null){
            tbOrder.setEndDate(DateUtils.addMonths(tbOrder.getBeginDate(), 1));
        }*/
        Date date=tbOrder.getEndDate();
        if(date!=null){
            date.setHours(23);
            date.setMinutes(59);
            date.setSeconds(59);
        }
        tbOrder.setPage(tbOrderPage);
        List list = tbOrderMapper.findByPage(tbOrder);
        tbOrderPage.setList(list);
        return tbOrderPage;
    }
    //代理商到处信息时信息时的模板操作
    public Page<TbOrder> exportTenement(Page<TbOrder> page,TbOrder tbOrder){
        // 设置默认时间范围，默认当前月
        if (tbOrder.getBeginDate() == null){
            tbOrder.setBeginDate(DateUtils.setDays(DateUtils.parseDate(DateUtils.getDate()), 1));
        }
        if (tbOrder.getEndDate() == null){
            tbOrder.setEndDate(DateUtils.addMonths(tbOrder.getBeginDate(), 1));
        }
        tbOrder.setPage(page);
        List list = tbOrderMapper.findByPage(tbOrder);
        for(int i=0;i<list.size();i++){
            TbOrder tbOrder1=(TbOrder) list.get(i);
            if(tbOrder1.getOrderState()==0){
                tbOrder1.setPayName("未确认（未支付）");
            }else if(tbOrder1.getOrderState()==1){
                tbOrder1.setPayName("已确认(已支付)");
            }else if(tbOrder1.getOrderState()==2){
                tbOrder1.setPayName("待发货");
            }else if(tbOrder1.getOrderState()==3){
                tbOrder1.setPayName("已发货");
            }else if(tbOrder1.getOrderState()==4){
                tbOrder1.setPayName("已完成");
            }else if(tbOrder1.getOrderState()==5){
                tbOrder1.setPayName("已取消");
            }else if(tbOrder1.getOrderState()==6){
                tbOrder1.setPayName("已关闭");
            }
        }
        page.setList(list);
        return page;
    }
    @Transactional(readOnly = false)
    public Page<TbOrder> findReserveByPage(Page<TbOrder> tbOrderPage, TbOrder tbOrder) {
        tbOrder.setPage(tbOrderPage);
        List list = tbOrderMapper.findReserveByPage(tbOrder);
        tbOrderPage.setList(list);
        return tbOrderPage;
    }
    @Transactional(readOnly = false)
    public Page<TbOrder> findOrderByPage(Page<TbOrder> tbOrderPage, TbOrder tbOrder) {
        if (tbOrder.getBeginDate() == null){
            tbOrder.setBeginDate(DateUtils.setDays(DateUtils.parseDate(DateUtils.getDate()), 1));
		}
		if (tbOrder.getEndDate() == null) {
            tbOrder.setEndDate(DateUtils.addMonths(tbOrder.getBeginDate(), 1));
        }
        tbOrder.setPage(tbOrderPage);
        List<TbOrder> list = tbOrderMapper.findOrderByPage(tbOrder);
        for(TbOrder order:list){
            if(order.getDelivery()==null){
                order.setDelivery(new Byte("2"));
            }
        }
        tbOrderPage.setList(list);
        return tbOrderPage;
    }
    // 用户
    @Transactional(readOnly = false)
    public Page<TbOrder> findUserReserveByPage(Page<TbOrder> tbOrderPage, TbOrder tbOrder) {
        tbOrder.setPage(tbOrderPage);
        List list = tbOrderMapper.findUserReserveByPage(tbOrder);
        tbOrderPage.setList(list);
        return tbOrderPage;
    }
    @Transactional(readOnly = false)
    public void editGudenStuffState(Map map){
        tbOrderMapper.editGudenStuffState(map);
    }


    @Transactional(readOnly = false)
    public void insert(TbOrder tbOrder){
        tbOrderMapper.insertTbOrder(tbOrder);
    }


    public void editOrderState(String orderNo) {
        TbOrder order = new TbOrder();
        order.setPayState(new Byte("1"));
        order.setOrderState(new Byte("4"));
        order.setOrderNo(orderNo);
        tbOrderMapper.editOrderState(order);
    }

    public void updateStatus(String orderNo) {
        TbOrder order = new TbOrder();
        order.setOrderNo(orderNo);
        order.setOrderState(new Byte("4"));
        tbOrderMapper.updateStatus(order);
    }

    public void deleteOrder(Integer orderId) {
        tbOrderMapper.deleteByPrimaryKey(orderId);
        tbOrderProductMapper.deleteOrder(orderId);
    }

    public TbOrder insertOrder(HttpServletRequest request, String str) {
        User user= UserUtils.getUser();
        String agentId=user.getAgentId();
        TbShop tbShop=new TbShop();
        tbShop.setUid(user.getId());
        TbShop tbShop1= tbShopMapper.selectByUid(tbShop);    //根据商户（当前用户ID）找到商户

        //变量用于判断商品属于什么类型
        String productType="";
        BigDecimal orderAmount=new BigDecimal(0);
        String str1[]=str.split(";");
        //下面的for循环主要计算订单总额
        for (String str2:str1) {
            String str3[]=str2.split(",");
            int agentProductId=0;    //代理商品ID
            int productNum=0;   //商品数量
            agentProductId=Integer.parseInt(str3[0]);
            productNum=Integer.parseInt(str3[1]);
            TbAgentProduct tbAgentProduct=new TbAgentProduct();
            tbAgentProduct=tbAgentProductMapper.getAgentProductByIdAndAgentId(agentProductId,user.getAgentId());
            if(null!=tbAgentProduct){
                //订单总额的计算
                orderAmount = orderAmount.add(tbAgentProduct.getPrice().multiply( new BigDecimal(productNum) ) )  ;
            }
            TbProduct tbProduct = tbProductService.selectByPrimaryKey(tbAgentProduct.getProductId());
            TbCategory tbCategory = tbCategoryService.getTbCategory(tbProduct.getCategoryId());
            productType= tbCategory.getParentIds().substring(4,5);
        }
        /**
         *订单的处理
         */
        String uid=user.getId();
        TbShop shop = new TbShop();
        shop.setUid(uid);
        shop = tbShopMapper.selectByUid(shop);
        TbOrder tbOrder=new TbOrder();
        String orders=request.getParameter("orders");
        tbOrder.setUid(shop.getId()+"");
        tbOrder.setPlatFormType(3);
        tbOrder.setChannelId(1);
        tbOrder.setContactName(user.getName());
        tbOrder.setContactMobile(user.getMobile());
        tbOrder.setOrderAmount(orderAmount);
        tbOrder.setPayName("微信");
        tbOrder.setPayAmount(orderAmount);
        tbOrder.setCreateTime(new Date());
        tbOrder.setUpdateTime(new Date());
        tbOrder.setPayNote(request.getParameter("remarks"));
        tbOrder.setOrderDescribe(request.getParameter("remarks"));
        tbOrder.setAddressId(shop.getCommunityId());
        tbOrder.setMchId(1);//固定传1
        tbOrder.setRefundReason("");
        tbOrder.setRefundState(new Byte("0"));
        tbOrder.setRefundNotifyUrl("");
        tbOrder.setRefundIngAmount(new BigDecimal("0"));
        tbOrder.setOrderSubject("店铺进货");
        tbOrder.setExceptionRefundNotify("");
        tbOrder.setRefundNotifyUrl("");
        tbOrder.setCloseNotifyUrl("");
        tbOrder.setOrderUrl("");
        tbOrder.setShowUrl(orders);
        tbOrder.setExtraParam(productType);
        tbOrder.setService("");
        tbOrder.setShopId(shop.getId());
        tbOrder.setBeneficiaryName("");
        tbOrder.setProductType(productType);

        tbOrder.setOrderNo(NumberGenerator.getNextStreamNo());
        tbOrder.setOrderState((byte)0);
        tbOrder.setPayState((byte)0);
        tbOrder.setNotifyUrl(""+ Configuration.getInstance().getStringValue("backUrl.url","")
                +"/AgentProduct/updateAgentProduct?orderNo="
                +tbOrder.getOrderNo()+"&agentId="+agentId+"");
        tbOrder.setIsDelete(new Byte("0"));
        String url = Configuration.getInstance().getStringValue("backUrl.url","");
        tbOrder.setOrderUrl(""+url+"/bbc/order/pay?agentId="+agentId+"");
        tbOrderMapper.insertTbOrder(tbOrder);
        for (String str2:str1) {
            String str3[] = str2.split(",");
            int agentProductId = Integer.parseInt(str3[0]);    //商品ID
            int productNum = Integer.parseInt(str3[1]);   //商品数量
            //根据代理商商品id和商品数量减库存，代理商库存

            TbAgentProduct tbAgentProduct=tbAgentProductMapper.getAgentProductByIdAndAgentId(agentProductId,user.getAgentId());
            if(null!=tbAgentProduct){
                TbOrderProduct tbOrderProduct = new TbOrderProduct();
                tbOrderProduct.setOrderId(tbOrder.getId());
                tbOrderProduct.setProductId(tbAgentProduct.getProductId());
                tbOrderProduct.setProductName(tbAgentProduct.getTitle());
                tbOrderProduct.setShopId(shop.getId());
                tbOrderProduct.setAttr(tbAgentProduct.getAttr());
                tbOrderProduct.setAgentProductId(agentProductId);
                tbOrderProduct.setPrice(tbAgentProduct.getPrice());
                tbOrderProduct.setQuantity(productNum);
                tbOrderProduct.setCreateTime(new Date());
                tbOrderProduct.setUpdateTime(new Date());
                tbOrderProduct.setIsDelete(new Byte("0"));
                tbOrderProductMapper.insert(tbOrderProduct);
                //修改该店铺下的预定订单 为已进货 根据商品查找订单
                Map map= new HashMap();
                map.put("productId",tbAgentProduct.getProductId());
                map.put("shopId",shop.getId());
                map.put("attr",tbAgentProduct.getAttr());
                int count = tbShopProductDao.updateOrderToAllreadayReverse(map);
                System.out.print(count);
            }
        }
        //店铺下单成功后，向信息表中插入一条数据
        TbMsgNotify tbMsgNotify=new TbMsgNotify();
        //将店铺的代理商放进信息表中
        tbMsgNotify.setUid(UserUtils.getUser().getAgentId());
        Date date=new Date();
        tbMsgNotify.setCreateTime(date);
        tbMsgNotify.setUpdateTime(date);
        tbMsgNotify.setStatus("0");
        tbMsgNotify.setTitle("店铺进货");
        tbMsgNotify.setContent(UserUtils.getUser().getName()+"的"+shop.getName()+"进货");
        tbMsgNotify.setShopUserId(UserUtils.getUser().getId());
        tbMsgNotify.setShopUserId(shop.getId()+"");
        tbMsgNotifyService.insertMsg(tbMsgNotify);

        tbOrder.setAgentName(agentId);
        tbOrder.setProductType(productType);
        return tbOrder;
    }

    public Page<TbOrder> findProByPage(Page<TbOrder> tbOrderPage, TbOrder tbOrder) {
        if (tbOrder.getBeginDate() == null){
            tbOrder.setBeginDate(DateUtils.setDays(DateUtils.parseDate(DateUtils.getDate()), 1));
        }
        if (tbOrder.getEndDate() == null) {
            tbOrder.setEndDate(DateUtils.addMonths(tbOrder.getBeginDate(), 1));
        }
        tbOrder.setPage(tbOrderPage);
        List<TbOrder> list = tbOrderMapper.findProByPage(tbOrder);
        for(TbOrder order:list){
            if(order.getDelivery()==null){
                order.setDelivery(new Byte("2"));
            }
        }
        tbOrderPage.setList(list);
        return tbOrderPage;
    }

    public TbOrder selectOrderById(String orderId) {
        return tbOrderMapper.selectByPrimaryKey(Integer.valueOf(orderId));
    }


    public void updatePreCancelOrder(TbOrderProduct tbOrderProduct,Integer id) {
        List<TbOrder> list = tbOrderMapper.selectPreCancelOrder(tbOrderProduct.getProductId());
        if(!CollectionUtils.isEmpty(list)){
            for (TbOrder tbOrder1 :list){
                tbOrder1.setSourceBusinessId("0");
                tbOrderMapper.updateByPrimaryKeySelective(tbOrder1);
            }
        }
        TbOrder tbOrder = tbOrderMapper.selectByPrimaryId(id);
        tbOrder.setOrderState((byte)5);
        tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
    }
}
